<template>
  <div class="container">
    <h2>自适应窗口变化-基础柱状图-渐变</h2>
    <div class="chart-container">
      <div id="basicBarResize" style="height:500px"></div>
    </div>
  </div>
</template>

<script>
export default {
  name: "basicBarResize",
  data() {
    return {
      screenWidth: document.body.clientWidth, // 初始化宽度
      timer: null, // 定时器flag
      myEchart: null, // 用于保存echarts 的实例
      option: {
        xAxis: {
          type: "category",
          data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
        },
        yAxis: {
          type: "value",
        },
        series: [
          {
            data: [120, 200, 150, 80, 70, 110, 130],
            type: "bar",
            itemStyle: {
              color: {
                type: "linear",
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 0,
                    color: "#f48107",
                  },
                  {
                    offset: 1,
                    color: "#f745f3",
                  },
                ],
                globalCoord: false,
              },
            },
          },
        ],
      },
    };
  },
  mounted() {
    // 挂载window.onresize方法
    const that = this;
    window.onresize = () => {
      return (() => {
        window.screenWidth = document.body.clientWidth;
        that.screenWidth = window.screenWidth; // 新的窗口值,给this.screenWidth
      })();
    };
    // 初始化Echarts
    this.getLineChart();
  },
  watch: {
    // 监听变化
    screenWidth(newval) {
      // 为了避免频繁触发resize函数导致页面卡顿，使用定时器
      if (!this.timer) {
        this.screenWidth = newval; // 一旦监听到的screenWidth值改变，就将其重新赋给data里的screenWidth
        this.timer = true;
        let that = this;
        this.barChart.resize();
        setTimeout(function () {
          console.log("resize = ", that.screenWidth); // 打印screenWidth变化的值
          that.timer = false;
        }, 100);
      }
    },
  },
  methods: {
    // 设置折线图
    getLineChart() {
      this.barChart = this.$echart.init(
        document.getElementById("basicBarResize")
      );
      this.myEchart = this.barChart;
      this.barChart.setOption(this.option);
    },
  },
};
</script>

<style lang="less">
.chart-container {
  canvas {
    // width: 200px !important;
  }
}
</style>